﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Linq;
using XingLucifer.IBase.Enums;

namespace Kinlo.MESDocking
{
    /// <summary>
    /// 一键点检
    /// </summary>
    public class OneClickSpotCheck : MESInteractionBase
    {
        public OneClickSpotCheck(Action<string, string, string, string, string, long, DateTime, string, string, string> log, Action<string, string, string> dialog)
            : base(log, dialog, "一键点检")
        {

        }

        public override ResultTypes Interaction(string url, int timeout, int reconnect_count, DateTime dateTime, ProductionData[] production, Dictionary<string, object> parameters)
        {
            _stopwatch.Restart();
            try
            {
                string json = JsonSerializer.Serialize(parameters["parameter"], HttpHelper.Options);
                var result = Post(json, url, timeout, reconnect_count);
                _stopwatch.Stop();
                _log?.Invoke("", _name, result.Item1 ? result.Item2 : "请求异常", json, result.Item1 ? result.Item2 : "请求异常",
                    _stopwatch.ElapsedMilliseconds, dateTime, parameters["machineNo"].ToString(), parameters["producttype"].ToString(), "oneClickSpotCheck");
                if (result.Item1)
                {
                    Dictionary<string, string> result_json = JsonSerializer.Deserialize<Dictionary<string, string>>(result.Item2, HttpHelper.Options);
                    if (result_json["Return_Code"] != "OK")
                    {
                        _dialog?.Invoke(_name, "E501", result_json["Msg"]);
                        switch (result_json["Return_Code"])
                        {
                            case "Alarm":
                            case "Stop":
                                return ResultTypes.MES_停机;
                            case "Tips":
                                return ResultTypes.合格;
                        }
                        return ResultTypes.MES_NG;
                    }
                }
                else
                {
                    _dialog?.Invoke(_name, "ERROR", result.Item2);
                    return ResultTypes.MES_NG;
                }
                return ResultTypes.合格;
            }
            catch (Exception ex)
            {
                _dialog?.Invoke(_name, "ERROR", $"异常：{ex}");
                return ResultTypes.MES_NG;
            }
        }
    }
}
